<template>
  <div class="createPost-container">
    <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="100px">
      <div class="createPost-main-container">
        <el-row>
          <el-col v-show="postForm.examState===1" :span="4">
            <b>请选择接收用户</b>
            <el-tabs v-model="selectUserMode" @tab-click="tabChange">
              <el-tab-pane label="按部门选择" name="selectUserByDept">
                <el-input
                  v-model="filterText"
                  placeholder="输入关键字进行过滤"
                  style="margin:10px 0"
                />
                <el-tree
                  ref="tree"
                  show-checkbox
                  node-key="id"
                  :expand-on-click-node="false"
                  :data="treedata"
                  :filter-node-method="filterNode"
                  :default-checked-keys="checkedUser"
                />
              </el-tab-pane>
              <el-tab-pane label="按标签组选择" name="selectUserByGroup">
                <el-input
                  v-model="filterText2"
                  placeholder="输入关键字进行过滤"
                  style="margin:10px 0"
                />
                <el-tree
                  ref="tree2"
                  show-checkbox
                  node-key="id"
                  :expand-on-click-node="false"
                  :data="treedata2"
                  :filter-node-method="filterNode2"
                  :default-checked-keys="checkedUser2"
                />
              </el-tab-pane>
            </el-tabs>
            <el-button type="primary" :loading="loading" style="margin-top:10px;" @click="submitForm">保存</el-button>
          </el-col>
          <el-col :span="20">
            <b v-if="postForm.examState!==1" style="color:red;margin-left:100px">注：只有未开始的考试才能修改参与人员</b>
            <el-form-item prop="title" label="考试名称">
              {{ postForm.title }}
            </el-form-item>
            <el-form-item prop="daterange" label="时间段">
              {{ postForm.daterange[0] }} 至
              {{ postForm.daterange[1] }}
            </el-form-item>
            <el-form-item prop="daterange" label="人员">
              <el-table :data="postForm.reservedPersons" border fit highlight-current-row style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column align="center" prop="realName" label="姓名" width="120" />
                <el-table-column align="center" prop="email" label="邮箱" width="250" />
                <el-table-column align="center" prop="deptName" label="部门" width="200" />
                <el-table-column align="center" prop="postName" label="职务" />
                <el-table-column align="center" prop="examTime" label="考试时间" width="200" />
                <el-table-column align="center" prop="score" label="考试成绩" width="100" />
                <el-table-column align="center" prop="makeUpTime" label="补考时间" width="200" />
                <el-table-column align="center" prop="makeUpScore" label="补考成绩" width="100" />
                <!-- <el-table-column align="center" prop="state" label="学习时长" width="120">
                  <template slot-scope="scope">
                    {{ formatStudyDuration(scope.row.studyDuration) }}
                  </template>
                </el-table-column> -->
                <el-table-column align="center" prop="state" label="学习状态" width="120">
                  <template slot-scope="scope">
                    {{ id2userState(scope.row.state) }}
                  </template>
                </el-table-column>
              </el-table>
              <el-button type="primary" :disabled="!postForm.published" :loading="messageLoading" style="margin-top:10px;" @click="sendMessage">发送{{ postForm.examState===3?'成绩通知':'考试提醒' }}</el-button>
              <span v-if="!postForm.published" style="font-weight:bolder;color:red;padding-left:20px">未发布，发布后才能发送消息</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
const defaultForm = {
  id: null,
  userList: [],
  title: '', // 文章题目
  daterange: [],
  content: '' // 文章内容
}
export default {
  name: 'ArticleDetail',
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    const validateRequire2 = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      multipleSelection: [],
      messageLoading: false,
      selectUserMode: 'selectUserByDept',
      filterText: '',
      filterText2: '',
      treedata: [],
      treedata2: [],
      timestamp2: 0,
      dialogVisible: false,
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      deptOption: [],
      userOption: [],
      rules: {
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        userList: [{ validator: validateRequire }],
        daterange: [{ validator: validateRequire2 }]
      },
      tempRoute: {},
      infoType: 0,
      checkedUser: [],
      checkedUser2: []
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        console.log('val:' + val)
        this.treedata2 = []
        this.checkedUser2 = []
        this.checkedUser = []
        this.getData(this.infoid)
        this.getGroup()
      },
      immediate: true
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    this.getDepts()
    this.getGroup()
    this.getUsers()
  },
  created() {
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    sendMessage() {
      if (this.multipleSelection.length > 0) {
        let message = ''
        if (this.postForm.examState === 3) {
          message = '您确定要给选中人员发送成绩通知吗？'
        } else {
          message = '您确定要给选中人员发送考试提醒吗？'
        }
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const para = {
            examId: this.postForm.id,
            messageType: this.postForm.examState === 3 ? 2 : 1,
            userIds: this.multipleSelection.map(item => item.userId)
          }
          this.messageLoading = true
          this.$http
            .post('/api/busExamination/sendExaminationMessage', para)
            .then(response => {
              this.messageLoading = false
              if (response.data.success === true) {
                this.$message({
                  message: '发送成功',
                  type: 'success'
                })
                this.messageDialogVisible = false
              } else {
                console.log('发送失败:' + response.data.message)
                this.$message({
                  message: '发送失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              this.messageLoading = false
              console.log(error)
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        this.$message({
          message: '请至少选择一位用户',
          type: 'danger'
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    tabChange() {
      console.log('tabChange')
      // this.$refs.tree.setCheckedKeys([0])
      // this.$refs.tree2.setCheckedKeys([0])
    },
    formatStudyDuration(mins) {
      if (mins) {
        const hours = parseInt(mins / 60)
        const leftmins = mins % 60
        return hours ? hours + '小时' + (leftmins ? leftmins + '分钟' : '') : mins + '分钟'
      } else {
        return '0分钟'
      }
    },
    id2userState(id) {
      if (id) {
        switch (id) {
          case 0:
            return '待考试'
          case 1:
            return '合格'
          case 2:
            return '补考合格'
          case 3:
            return '不合格'
        }
      } else {
        return '待考试'
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    filterNode2(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    detail() {
      this.dialogVisible = true
      this.timestamp2 = new Date().getTime()
    },
    getDepts() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('/api/sysDept/queryPage', para)
        .then(response => {
          if (response.data.success === true) {
            this.deptOption = []
            for (const item of response.data.result.records) {
              this.deptOption.push({ label: item.deptName, value: item.id })
              this.userOption.push({ label: item.deptName, options: [] })
              this.treedata.push({ id: item.id + 10000, label: item.deptName, children: [] })
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getGroup() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('/api/busGroup/queryGroupByPage', para)
        .then(response => {
          if (response.data.success === true) {
            console.log('resultgroup')
            console.log(response.data.result.records)
            const checkedUser2 = []
            for (const item of response.data.result.records) {
              // 为了防止作为key的用户id重复，选择或取消时无法取消重复的id，将id前面增加标签组id_加以区分
              this.treedata2.push({ id: 'g_' + item.id, label: item.title, children: item.membersArray.map(it => {
                if (this.checkedUser.includes(it.id)) { // 按标签组选择模式回显选中人员
                  checkedUser2.push(item.id + '_' + it.id)
                }
                return { id: item.id + '_' + it.id, label: it.realName + '(' + it.deptName + ')' }
              }) })
            }
            this.$nextTick(() => {
              this.checkedUser2 = checkedUser2
            })
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getUsers() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('/api/sysUser/queryUserPage', para)
        .then(response => {
          if (response.data.success === true) {
            for (const item of response.data.result.records) {
              if (item.deptName && item.deptName !== '') {
                const theDept = this.userOption.filter((p) => {
                  return p.label === item.deptName
                })
                theDept[0].options.push({ label: item.realName, value: item.id })
                const treeDept = this.treedata.find((p) => {
                  return p.label === item.deptName
                })
                if (item.sysRoleId !== 1) { treeDept.children.push({ label: item.realName, id: item.id }) }
              }
            }
            this.treedata = this.treedata.filter(item => item.children.length > 0)
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getData(id) {
      console.log('id')
      console.log(id)
      if (id) {
        this.infoLoading = true
        this.$http
          .get('/api/busExamination/getDetailById?&id=' + id)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              this.postForm = response.data.result
              this.postForm.daterange = [response.data.result.beginTime, response.data.result.endTime]
              this.postForm.content = response.data.result.remark
              this.checkedUser = response.data.result.reservedPersons.map(item => item.userId)
              console.log(response.data.result.reservedPersons.map(item => item.userId))
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
          this.postForm = Object.assign({}, defaultForm)
          // this.$refs.editor.setContent('')
          if (this.$refs.editor) {
            this.$refs.editor.setContent('')
          }
        })
      }
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          let checkedUser = []
          if (this.selectUserMode === 'selectUserByDept') {
            checkedUser = this.$refs.tree.getCheckedKeys()
            if (!checkedUser || checkedUser.length === 0) {
              this.$message({
                message: '至少选一个接收用户',
                type: 'error'
              })
              return
            }
          } else if (this.selectUserMode === 'selectUserByGroup') {
            checkedUser = this.$refs.tree2.getCheckedKeys()
            if (!checkedUser || checkedUser.length === 0) {
              this.$message({
                message: '至少选一个接收用户',
                type: 'error'
              })
              return
            }
            // 先过滤掉id为g_开头的标签组节点，然后再把人员节点去掉_和_前面的标签组id
            checkedUser = checkedUser.filter(item => item.split('_')[0] !== 'g').map(item => item.split('_')[1])
          }
          // 去重
          checkedUser = [...new Set(checkedUser)]
          const day = new Date()
          day.setTime(day.getTime())
          const para = {
            id: this.postForm.id,
            userList: checkedUser.filter(item => item < 10000)
            // deptIds: this.postForm.deptIds
          }
          this.loading = true
          this.$http
            .post('/api/busExamination/saveExamination', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.postForm.status = 'published'
                this.postForm = Object.assign({}, defaultForm)
                this.filterText = ''
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
              } else {
                console.log('保存失败:' + response.data.message)
                this.$message({
                  message: '保存失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
